<template>
  <div class="hour-box-body">
    <div
      v-for="item in tableRows"
      :key="item"
      :class="[
        'hour-picker-item',
        item === selectedHour ? 'hour-picker-item-selected' : '',
      ]"
      @click="handleCheck(item)"
    >
      {{ item }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'HourTable',
  props: {
    // 选中的日期(选中渲染)
    selectedHour: {
      type: String,
      required: true,
    },
    // 小时间隔
    hourInterval: {
      type: Number,
    },
    // 自定义时间显示内容
    customHours: {
      type: Array,
    },
  },
  data() {
    return {};
  },
  computed: {
    tableRows() {
      if (this.customHours.length) {
        return [...this.customHours];
      } else {
        let interval, length;
        if (24 % this.hourInterval === 0) {
          length = 24 / this.hourInterval;
          interval = this.hourInterval;
        } else {
          length = 24;
          interval = 1;
        }
        const data = [];
        for (let i = 0; i < length; i++) {
          let d = i * interval;
          d = d > 9 ? d.toString() : '0' + d;
          data.push(d);
        }
        return data;
      }
    },
  },
  watch: {
    selectedHour(val) {
      if (!this.tableRows.includes(val)) {
        this.$emit('onSelectHour', this.tableRows[0]);
      }
    },
  },
  methods: {
    handleCheck(val) {
      this.$emit('onSelectHour', val);
    },
    // 初始化，如果下列选项中没有选中的小时，则默认选中第一个
    handleInitData() {
      const flag = this.tableRows.includes(this.selectedHour);
      if (!flag) {
        this.$emit('onSelectHour', this.tableRows[0]);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.hour-box-body {
  display: flex;
  flex-wrap: wrap;
  max-width: 240px;
  .hour-picker-item {
    line-height: 28px;
    width: 40px;
    text-align: center;
    cursor: pointer;
  }
  .hour-picker-item-selected {
    background-image: url('../../imgs/date-selected.png');
    background-position: center center;
    background-repeat: no-repeat;
  }
}
</style>
